package com.example.zhu.controller;

import com.example.zhu.Utils.JwtUtils;
import com.example.zhu.VO.MenuVO;
import com.example.zhu.dto.Reply;
import com.example.zhu.dto.ResultCode;
import com.example.zhu.dto.User;
import com.example.zhu.Mapper.UserMapper;
import com.example.zhu.service.Impl.MenuServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private MenuServiceImpl menuService;
    @PostMapping("/login")
    public void login(HttpServletRequest request,
                      HttpServletResponse response,@RequestBody User user ) throws IOException {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        User LoginUser = userMapper.SelectUserByUP(user);
        if (LoginUser != null) {
            log.info("用户登录成功");
            Map<String, Object> map = new HashMap<>();
            map.put("username",LoginUser.getUsername());
            String token = JwtUtils.getToken(map);
            List<MenuVO> menuTree = menuService.getMenuTreeByDeptIdAndRole(user);
            response.setHeader("token",token);
            map.put("userInfo",LoginUser);
            map.put("token", token);
            map.put("menuList",menuTree);
            Gson gson = new Gson();
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(Reply.success(ResultCode.USER_LOGIN_SUCCESS.getMsg(), gson.toJson(map)).toString());
            return;
        }
        //返回json形式的错误信息
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write(new ObjectMapper().writeValueAsString(Reply.failed(ResultCode.USERNAME_PWD_ERROR.getCode(),ResultCode.USERNAME_PWD_ERROR.getMsg(),null)));
        response.getWriter().flush();
        return;


    }
}
